﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Quebec.Silverlight.Animations
{
	public abstract class AnimationBase
	{
		public event EventHandler AnimationCompleted;

		protected virtual void OnAnimationCompleted(EventArgs e)
		{
			if (AnimationCompleted != null)
				AnimationCompleted(this, e);
		}

		protected virtual string ResourceKey
		{
			get
			{
				return GetType().FullName;
			}
		}

		protected abstract Storyboard CreateStoryboard();
		protected abstract void ApplyValues(Storyboard storyboard);

		public virtual void Apply(FrameworkElement element)
		{
			if (element == null)
				throw new ArgumentNullException("element");

			Storyboard storyboard = null;

			if (element.Resources.Contains(ResourceKey))
			{
				storyboard = element.Resources[ResourceKey] as Storyboard;
				storyboard.Pause();
			}
			else
			{
				storyboard = CreateStoryboard();
				element.Resources.Add(ResourceKey, storyboard);

				foreach (var timeline in storyboard.Children)
				{
					Storyboard.SetTarget(timeline, element);
				}
			}

			ApplyValues(storyboard);

			storyboard.Completed += OnStoryboardCompleted;
			storyboard.Begin();
		}

		protected virtual void OnStoryboardCompleted(object sender, EventArgs e)
		{
			OnAnimationCompleted(EventArgs.Empty);
		}
	}
}
